package com.securityjava.security;


import com.securityjava.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 执行登录接口后,进行登录逻辑处理类
 */
@Component
public class LoginService {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    PasswordEncoder passwordEncoder;


    @Resource
    private AuthenticationManager authenticationManager;

    public Map login(String username, String password) throws Exception {//拿到Controller层传入的账号密码
        Map map = null;
        // 用户验证
        try {
            Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
            UserDetails loginUser = (UserDetails) authentication.getPrincipal();
            if (loginUser != null) {
                //密码正确
                map = jwtTokenUtils.getToken(username);//生成携带用户名的Token
                map.put("code", 200);
                map.put("msg", "登录成功");
                map.put("username", username);//返回给前端用户名方便前端渲染
                return map;//返回给前端一个含有Token的map集合
            } else {
                throw new Exception("登录异常");
            }
        }catch (Exception ex)
        {
            throw new Exception("登录异常"+ex.getMessage());
        }



    }
}
